import sys
import datetime
from PyQt4 import QtCore, QtGui


sys.path.append("UI")
import os
home = os.getcwd()
os.chdir("UI")
os.system('python Builder.py')
os.chdir(home)

VERSION = '001ALPHA'

import People
import Events
import PeopleOnEvents
import TripExpenses
import SubGroupExpenses
import PeopleInSubGroup
import MySQL
import DataBase


#from UI import *
from UI.CreateNewEventDiag import Ui_CreateNewEventDiag
from UI.MainGui import Ui_MainWindow
#from UI.AddPersonDiag import Ui_AddPersonDiag
from UI.AdminUserDetailsDiag import Ui_AdminUserDetailsDiag
from UI.SignInDiag import Ui_SignInDiag
from UI.UserDetailsDiag import Ui_UserDetailsDiag
from UI.ConfirmDiag import Ui_ConfirmDiag
from UI.EditEventDiag import Ui_EditEventDiag
from UI.AddPersonToEventDiag import Ui_AddPersonToEventDiag
from UI.SelectEventDiag import Ui_SelectEventDiag
from UI.SelectEventDiagAdmin import Ui_SelectEventDiagAdmin
from UI.EventDatesSelectDiag import Ui_EventDatesSelectDiag
#from EventDatesSelectDiagAdmin import Ui_EventDatesSelectDiagAdmin
from UI.AddTripExpenseDiag import Ui_AddTripExpenseDiag
from UI.ViewTripExpenseDiag import Ui_ViewTripExpenseDiag
from UI.EditTripExpenseDiag import Ui_EditTripExpenseDiag
from UI.AddSubGroupExpenseDiag import Ui_AddSubGroupExpenseDiag
from UI.AddPersonToSubGroupDiag import Ui_AddPersonToSubGroupDiag
from UI.ViewSubGroupExpenseDiag import Ui_ViewSubGroupExpenseDiag
from UI.ViewExpenseSummaryDiag import Ui_ViewExpenseSummaryDiag
from UI.ViewSpendingSummaryDiag import Ui_ViewSpendingSummaryDiag
from UI.SelectNewPersonDiag import Ui_SelectNewPersonDiag

global Admin
global PID
global EventId

class ConfirmDiag(QtGui.QDialog, Ui_ConfirmDiag):
    def __init__(self, Message):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.label.setText(Message)
        self.ID = 0

class SelectNewPerson(QtGui.QDialog, Ui_SelectNewPersonDiag):
    def __init__(self, People):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        for Person in People:
            Item = QtGui.QListWidgetItem("""%s %s"""% (Person.f_Name, Person.l_Name))
            Item.uniqueId = Person.PID
            self.listWidget.addItem(Item)
        self.listWidget.setCurrentRow(0)
    
    def GetPerson(self):
        return self.listWidget.currentItem().uniqueId
        
class SelectEvent(QtGui.QDialog, Ui_SelectEventDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        Events = Database.GetEventsPersonOn(PID)
        for Event in Events:
            self.listWidget.addItem("""ID:%d  EventName:%s"""% (Event.EID, Event.EventName))
        self.listWidget.setCurrentRow(0)
    
    def GetEvent(self):
        return int(self.listWidget.currentItem().text().split(' ')[0].replace('ID:',''))
        

        
class SelectEventAdmin(QtGui.QDialog, Ui_SelectEventDiagAdmin):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        Events = Database.Events.GetAllEvents()
        for Event in Events:
            self.listWidget.addItem("""ID:%d  EventName:%s"""% (Event.EID, Event.EventName))
        self.listWidget.setCurrentRow(0)
        self.connect(self.CreateNewEventButton, QtCore.SIGNAL("clicked()"), self.AddNewEvent)
    
    def GetEvent(self):
        return int(self.listWidget.currentItem().text().split(' ')[0].replace('ID:',''))
    
    def AddNewEvent(self):
        self.emit(QtCore.SIGNAL('NewEvent()'))

class AddPersonToSubGroup(QtGui.QDialog, Ui_AddPersonToSubGroupDiag):
    def __init__(self, People):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.People = People
        self.PopulateTable()
        
    def PopulateTable(self):
        for Person in self.People:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Person.PID))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 2, QtGui.QCheckBox())
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setTristate(False)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setCheckState(0)
            i = 0
            while (i < self.tableWidget.columnCount()):
                self.tableWidget.resizeColumnToContents(i)
                i = i + 1
                
    def GetAddedPeople(self):
        PIDS = []
        while self.tableWidget.rowCount() != 0:
            if self.tableWidget.cellWidget(0, 2).checkState() == 2:
                PIDS.append(int(self.tableWidget.item(0,0).text()))
            self.tableWidget.removeRow(0)
        return PIDS

class AddSubGroupExpense(QtGui.QDialog, Ui_AddSubGroupExpenseDiag):
    def __init__(self, Database, SGExpId = -1):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        global EventId
        global PID
        
        self.Database = Database
        self.Amount = '$0.0'
        self.CurrentPID = PID
        
        
        self.connect(self.ChangePersonButton, QtCore.SIGNAL("clicked()"), self.ChangePerson)
        
        self.SgExp_id = SGExpId
        if SGExpId != -1:    
            self.AddedPIDs=self.Database.PeopleInSubGroups.GetAllPeopleInSubgroupOnEvent(SGExpId, EventId)
        else:
            self.AddedPIDs=[[PID, 1.0]]
            
        
        
        self.connect(self.DoneButton, QtCore.SIGNAL("clicked()"), self.Finished)
        self.connect(self.ExpenseAmount, QtCore.SIGNAL("editingFinished()"), self.CheckAmount)
        self.connect(self.AddPersonButton, QtCore.SIGNAL("clicked()"), self.AddPerson)
        self.ExpenseAmount.setText(self.Amount)
        
        self.InitTable()
        self.PopulateTable()
        self.PopulatePersonData()
        
        
    def PopulatePersonData(self):
        Person = self.Database.People.GetPerson(PID = self.CurrentPID)
        self.PersonNameEdit.setText("""%s %s"""%(Person.f_Name, Person.l_Name))
        
    def ChangePerson(self):
        global EventId

        People = self.Database.GetPeopleOnEvent(EventId)
        self.SelectNewPersonDiag = SelectNewPerson(People)
        self.SelectNewPersonDiag.show()
        self.connect(self.SelectNewPersonDiag, QtCore.SIGNAL("accepted()"), self.ChangePersonUpdate)
        
    def ChangePersonUpdate(self):
        self.CurrentPID =  self.SelectNewPersonDiag.GetPerson()
        self.PopulatePersonData()
            
        
    def CheckAmount(self):
        Number, FloatCheck = self.ExpenseAmount.text().replace('$','').toFloat()
        if not FloatCheck:
            self.ExpenseAmount.setText(self.Amount)
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Input must be of type float")
            self.Message.show()
        else:
            if '$' not in self.ExpenseAmount.text():
                text = '$' + self.ExpenseAmount.text()
                self.ExpenseAmount.setText(text)
                self.Amount = text
        self.PopulateTable()
            
    def CheckExpenseTitle(self):
        Res = False
        if self.ExpenseTitle.text() != "":
            Res = True
        return Res
        
    def Finished(self):
        global EventId
        if self.CheckExpenseTitle():
            if self.SgExp_id == -1:
                Date = datetime.date(self.ExpenseDate.date().year(),
                                    self.ExpenseDate.date().month(),
                                    self.ExpenseDate.date().day())
                Amount = float(self.ExpenseAmount.text().replace('$',''))
                Desc = self.ExpenseTitle.text() + '\n\n' + self.ExpenseDesc.toPlainText()
                self.Database.AddSubGroupExpense(EventId, self.CurrentPID, Desc, Amount, Date, self.AddedPIDs)
            else:
                Expense =self.Database.SubGroupExpenses.GetSubGroupExpenses(SgExp_id = self.SgExp_id)[0]
                Expense.Amount = float(self.ExpenseAmount.text().replace('$',''))
                Expense.Desc = self.ExpenseTitle.text() + '\n\n' + self.ExpenseDesc.toPlainText()
                Expense.Date = datetime.date(self.ExpenseDate.date().year(),
                                    self.ExpenseDate.date().month(),
                                    self.ExpenseDate.date().day())
                self.Database.UpdateSubGroupExpense(Expense, self.AddedPIDs)
                
            
            self.accept()
        else:
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Please enter an expense name")
            self.Message.show()
    
    def AddPerson(self):
        global EventId
        PeopleOnEvent = self.Database.GetPeopleOnEvent(EventId)
        PeopleToAdd = []
        PIDsInList = []
        
        for PID, Prop in self.AddedPIDs:
            PIDsInList.append(PID)
            
        for Person in PeopleOnEvent:
            if Person.PID in PIDsInList:
                pass
            else:
                PeopleToAdd.append(Person)
        self.AddPersonDiag = AddPersonToSubGroup(PeopleToAdd)
        self.AddPersonDiag.show()
        self.connect(self.AddPersonDiag, QtCore.SIGNAL("accepted()"), self.AddPeopleSelect)
        
    def AddPeopleSelect(self):
        NewPeople = self.AddPersonDiag.GetAddedPeople()
        for PID in NewPeople:
            self.AddedPIDs.append([PID, 0.0])
        self.PopulateTable()
             
    def InitTable(self):
        PeopleDict = self.Database.People.GetAllPeopleDict()
        if self.SgExp_id != -1:
            Expense = self.Database.SubGroupExpenses.GetSubGroupExpenses(SgExp_id = self.SgExp_id)[0]
            self.CurrentPID = Expense.PID
            self.ExpenseAmount.setText("""$%.2f"""%Expense.Amount)
            self.Amount = self.ExpenseAmount.text()
            Desc = Expense.Desc.split('\n\n')
            self.ExpenseTitle.setText(Desc[0])
            self.ExpenseDesc.setPlainText(Desc[-1])
        else:
            self.ExpenseAmount.setText("""$%.2f"""%0.0)
            self.Amount = self.ExpenseAmount.text()
            
            self.ExpenseTitle.setText("")
            self.ExpenseDesc.setPlainText("")
        
            
    def PopulateTable(self):
        PeopleDict = self.Database.People.GetAllPeopleDict()
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        for PID, Prop in self.AddedPIDs:
            Person = PeopleDict[PID]
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            #self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Person.PID))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%.2f"""%(Prop*100)))
            #self.connect( self.tableWidget.item(self.tableWidget.rowCount()-1, 2), QtCore.SIGNAL("editingFinished()"), self.UpdateAmount)
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%.2f"""%(float(self.ExpenseAmount.text().replace('$',''))*(Prop))))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 3, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 3).uniqueId = """%d"""%Person.PID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 3).clicked.connect(self.OnDeletePerson)
        
            i = 0
            while (i < self.tableWidget.columnCount()):
                self.tableWidget.resizeColumnToContents(i)
                i = i + 1
    
    def OnDeletePerson(self):
        PIDToDelete = int(self.sender().uniqueId)
        NewList = []
        for PID, Prop in self.AddedPIDs:
            if PID != PIDToDelete:
                NewList.append([PID, Prop])
            
        self.AddedPIDs = NewList
        self.PopulateTable()
                    
class ViewSubGroupExpense(QtGui.QDialog, Ui_ViewSubGroupExpenseDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        global EventId
        self.EventId = EventId
        self.PopulateTable()
        
    def PopulateTable(self):
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        
        Expenses = self.Database.SubGroupExpenses.GetSubGroupExpenses(EID = self.EventId)
        People = self.Database.People.GetAllPeopleDict()
        for Expense in Expenses:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            #self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Expense.SgExp_id))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%d/%d/%d"""%(Expense.Date.day, Expense.Date.month, Expense.Date.year)))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s"""%Expense.Desc.split("\n\n")[0]))
            Person = People[Expense.PID]
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 3, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 4, QtGui.QTableWidgetItem("""$%.2f"""%Expense.Amount))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 5, QtGui.QComboBox())
            PIDsInGroup = self.Database.PeopleInSubGroups.GetAllPeopleInSubgroupOnEvent(Expense.SgExp_id, self.EventId)
            for PID, Prop in PIDsInGroup:
                Person = People[PID]
                self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).addItem("""%s %s"""%(Person.f_Name, Person.l_Name))

            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 6, QtGui.QPushButton("Edit"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 6).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 6).clicked.connect(self.OnEditEvent)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 7, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 7).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 7).clicked.connect(self.OnDeleteEvent)
      
    def OnEditEvent(self):
        SgExp_id =  int(self.sender().uniqueId)
        self.EditEventDiag = AddSubGroupExpense(self.Database, SgExp_id)
        self.EditEventDiag.show()
        self.connect(self.EditEventDiag, QtCore.SIGNAL("accepted()"), self.EditAccepted)
        
    def EditAccepted(self):
        self.PopulateTable()

    def OnDeleteEvent(self, Exp_Id):
        SgExp_id =  int(self.sender().uniqueId)
        self.ConfirmDelete = ConfirmDiag("Are you sure you want to delete?")
        self.ConfirmDelete.ID = str(SgExp_id)
        self.connect(self.ConfirmDelete, QtCore.SIGNAL("accepted()"), self.DeleteExpenseAccepted)
        self.ConfirmDelete.show()
        
    def DeleteExpenseAccepted(self):
        SgExp_id = int(self.ConfirmDelete.ID)
        self.Database.RemoveSubGroupExpense(SgExp_id)
        self.PopulateTable()
   
class ViewTripExpense(QtGui.QDialog, Ui_ViewTripExpenseDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        self.connect(self.AddNewExpenseBut, QtCore.SIGNAL("clicked()"), self.CreateNewExpense)
        self.PopulateTable()
        
        
    def PopulateTable(self):
        
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        Expenses = self.Database.Expenses.GetExpenses(EID = EventId)
        People = self.Database.People.GetAllPeopleDict()
        for Expense in Expenses:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            #self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Expense.TexID))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d/%d/%d"""%(Expense.Date.day, Expense.Date.month, Expense.Date.year)))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%s"""%Expense.Desc.split("\n\n")[0]))
            
            Person = People[Expense.PID]
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))

            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 3, QtGui.QTableWidgetItem("""%.2f"""%Expense.Amount))

            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 4, QtGui.QPushButton("Edit"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 4).uniqueId = """%d"""%Expense.TexID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 4).clicked.connect(self.OnEditExpense)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 5, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).uniqueId = """%d"""%Expense.TexID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).clicked.connect(self.OnDeleteExpense)
      
    def OnEditExpense(self):
        ExpId =  int(self.sender().uniqueId)
        self.EditExpenseDiag = EditTripExpense(self.Database, ExpId)
        self.EditExpenseDiag.show()
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("accepted()"), self.OnAcceptEdit)
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateTable)
        
    def OnAcceptEdit(self):
        if self.EditExpenseDiag.Result == 2:
            self.CreateNewExpense()
        self.PopulateTable()
        
    def OnDeleteExpense(self):
        button =  self.sender()
        Expense = self.Database.Expenses.GetExpenses(TexId = int(button.uniqueId))[0]
        self.ConfirmDelete = ConfirmDiag("Are you sure you want to delete %s?"%Expense.Desc.split("\n\n")[0])
        self.ConfirmDelete.ID = button.uniqueId
        self.connect(self.ConfirmDelete, QtCore.SIGNAL("accepted()"), self.DeleteExpenseAccepted)
        self.ConfirmDelete.show()
        
    def DeleteExpenseAccepted(self):
        self.Database.Expenses.RemoveExpense(int(self.ConfirmDelete.ID))
        self.PopulateTable()
        
    def CreateNewExpense(self):
        self.EditExpenseDiag = EditTripExpense(self.Database)
        self.EditExpenseDiag.show()
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("accepted()"), self.OnAcceptEdit)
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateTable)
        
class EditTripExpense(QtGui.QDialog, Ui_EditTripExpenseDiag):
    def __init__(self, DataBase, ExpenseId = -1):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Result = 1
        self.ExpenseId = ExpenseId
        self.Expense = None
        self.Database = DataBase
        self.currentPID = PID
        self.PopulateWindow()
        
    
    def PopulateWindow(self):
        if self.ExpenseId != -1:
            self.Expense = self.Database.Expenses.GetExpenses(self.ExpenseId)[0]
            Person = self.Database.People.GetPerson(PID = self.Expense.PID)
            self.currentPID = self.Expense.PID
            self.ExpenseName.setText(self.Expense.Desc.split('\n\n')[0])
            self.ExpenseOwner.setText("""%s %s"""%(Person.f_Name, Person.l_Name))
            #self.Date = Date
            #self.Desc = Desc
            self.ExpenseAmountEdit.setText("""$%0.2f"""%self.Expense.Amount)
            self.Amount = self.ExpenseAmountEdit.text()
        else:
            Person = self.Database.People.GetPerson(PID = PID)
            self.ExpenseOwner.setText("""%s %s"""%(Person.f_Name, Person.l_Name))
            self.ExpenseAmountEdit.setText("""$%0.2f"""%0.0)
            self.Amount = self.ExpenseAmountEdit.text()
        
        self.connect(self.AddAnotherExpenseBut, QtCore.SIGNAL("clicked()"), self.CreateNewEvent)   
        self.connect(self.FinishedBut, QtCore.SIGNAL("clicked()"), self.Finished)
        self.connect(self.CancelBut, QtCore.SIGNAL("clicked()"), self.Cancel)
        
        self.connect(self.ExpenseAmountEdit, QtCore.SIGNAL("editingFinished()"), self.CheckAmount)
    

    
    def CheckAmount(self):
        Number, FloatCheck = self.ExpenseAmountEdit.text().replace('$','').toFloat()
        if not FloatCheck:
            self.ExpenseAmountEdit.setText(self.Amount)
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Input must be of type float")
            self.Message.show()
        else:
            if '$' not in self.ExpenseAmountEdit.text():
                text = '$' + self.ExpenseAmountEdit.text()
                self.ExpenseAmountEdit.setText(text)
                self.Amount = text

    def CheckExpenseTitle(self):
        Res = False
        if self.ExpenseName.text() != "":
            Res = True
        return Res
   
    def Finished(self):
        if self.CheckExpenseTitle():
            if self.Expense != None and self.ExpenseId != -1:
                self.Expense.Desc = self.ExpenseName.text() + '\n\n' + self.ExpenseDesc.toPlainText()
                self.Expense.Amount = float(self.ExpenseAmountEdit.text().replace('$',''))
                self.Database.Expenses.UpdateExpense(self.Expense)
            else:
                Date = datetime.date(self.ExpenseDateEdit.date().year(),
                                  self.ExpenseDateEdit.date().month(),
                                  self.ExpenseDateEdit.date().day())
                ExpenseDesc = self.ExpenseName.text() + '\n\n' + self.ExpenseDesc.toPlainText()
                Amount = float(self.ExpenseAmountEdit.text().replace('$',''))
                self.Database.Expenses.AddExpense(EventId, self.currentPID, Date, ExpenseDesc, Amount)
                
            self.accept()
        else:
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Please enter an expense name")
            self.Message.show()
    
    def CreateNewEvent(self):
        self.Result = 2
        self.Finished()
    
    def Cancel(self):
        self.reject()

class DatesOnEventDiag(QtGui.QDialog, Ui_EventDatesSelectDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        global PID
        self.CurrentPID = PID
        
        self.tableWidget.resizeColumnToContents(2)
        self.connect(self.DoneButton, QtCore.SIGNAL("clicked()"), self.OnDone)
        
        self.PopulateWindow()
        
        
    def PopulateWindow(self):
        global EventId
        Delta = 0
        Event = self.Database.Events.GetEvent(EID = EventId)[0]
        StartDate = Event.StartDate
        EndDate = Event.EndDate
        PersonDates = self.Database.PeopleOnEvents.GetDatesPersonOnEvent(EventId, self.CurrentPID)
        while (StartDate + datetime.timedelta(Delta)) != EndDate + datetime.timedelta(1):
            Date = (StartDate + datetime.timedelta(Delta))
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d/%d/%d"""%(Date.day, Date.month, Date.year)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 1, QtGui.QCheckBox())
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setTristate(False)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setCheckState(2)
            self.connect(self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1), QtCore.SIGNAL("clicked()"),self.CheckAction)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 2, QtGui.QSpinBox())
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setRange(0,100)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setSingleStep(25)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setValue(100)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setEnabled(True)
            
            ##check on the users values.
            i = 0
            while i < len(PersonDates):
                if Date == PersonDates[i][0]:
                    self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setValue(PersonDates[i][1])
                    if PersonDates[i][1] == 0:
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setCheckState(0)
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setEnabled(False)
                    else:
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setCheckState(2)
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setEnabled(True)
                i = i + 1
            Delta = Delta + 1
        
    
    def GetDatesPresentFromWindow(self):
        i = 0
        PersonDates = []
        while i < self.tableWidget.rowCount():
            Date = self.tableWidget.item(i,0).text().split("""/""")
            Present = self.tableWidget.cellWidget(i, 2).value()
            PersonDates.append((datetime.date(int(Date[2]), int(Date[1]), int(Date[0])),Present))    
            i = i + 1
        return PersonDates
    
    def OnDone(self):
        global EventId
        self.Database.PeopleOnEvents.UpdateEventPeople(EventId,
                                              self.CurrentPID,
                                              self.GetDatesPresentFromWindow())
        self.accept()
        
    def CheckAction(self):
        i = 0
        PersonDates = []
        while i < self.tableWidget.rowCount():
            if self.tableWidget.cellWidget(i, 1).checkState() == 2:
                self.tableWidget.cellWidget(i, 2).setEnabled(True)
                self.tableWidget.cellWidget(i, 2).setValue(100)
            else:
                self.tableWidget.cellWidget(i, 2).setEnabled(False)
                self.tableWidget.cellWidget(i, 2).setValue(0)
            i = i + 1
        
class AdminCreateNewEvent(QtGui.QDialog, Ui_CreateNewEventDiag):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
  
class ManagePeopleOnEvent(QtGui.QDialog, Ui_AddPersonToEventDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        
        self.Database = Database
        
        self.PIDsInList = []
        PIDSOnEvent = self.Database.PeopleOnEvents.GetAllPeopleOnEvent(EventId)
        for PID, Dates in PIDSOnEvent:
            self.PIDsInList.append(PID)
        
        self.PopulateList()
        self.connect(self.AddPeopleButton, QtCore.SIGNAL("clicked()"), self.AddPerson)
        self.connect(self.DoneButton,QtCore.SIGNAL("clicked()"), self.Done)
    
    def PopulateList(self):
        global EventId
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        People = self.Database.People.GetAllPeopleDict()
        
        
        for PID in self.PIDsInList:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            Person = People[PID]
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 1, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).uniqueId = """%d"""%Person.PID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).clicked.connect(self.OnDeletePerson)
    
    def OnDeletePerson(self):
        PIDToDelete = int(self.sender().uniqueId)
        self.PIDsInList.remove(PIDToDelete)
        self.PopulateList()
    
    def AddPerson(self):
        global EventId
        People = self.Database.People.GetAllPeople()
        PeopleToAdd = []
        for Person in People:
            if Person.PID in self.PIDsInList:
                pass
            else:
                PeopleToAdd.append(Person)
                
        self.AddPersonDiag = AddPersonToSubGroup(PeopleToAdd)
        self.AddPersonDiag.show()
        self.connect(self.AddPersonDiag, QtCore.SIGNAL("accepted()"), self.AddPeopleSelect)
            
    def AddPeopleSelect(self):
        NewPeople = self.AddPersonDiag.GetAddedPeople()
        for PID in NewPeople:
            self.PIDsInList.append(PID)
        self.PopulateList()
            
    def Done(self):
        global EventId
        PIDSOnEvent = self.Database.PeopleOnEvents.GetAllPeopleOnEvent(EventId)
        for PID, Prop in PIDSOnEvent:
            if PID in self.PIDsInList:
                self.PIDsInList.remove(PID)
            else:
                self.Database.RemovePersonFromEvent(PID, EventId)
        if len(self.PIDsInList)> 0:
            Dates = []
            Delta = 0
            Event = self.Database.Events.GetEvent(EID = EventId)[0]
            StartDate = Event.StartDate
            EndDate = Event.EndDate
            while (StartDate + datetime.timedelta(Delta)) != EndDate:
                Dates.append((StartDate + datetime.timedelta(Delta),100))
                Delta = Delta + 1
            Dates.append((StartDate + datetime.timedelta(Delta),100))
            for PID in self.PIDsInList:
                self.Database.PeopleOnEvents.AddPersonToEvent(PID, EventId, Dates)
        self.accept()
           
class AdminEditEvent(QtGui.QDialog, Ui_EditEventDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        
        self.PopulateComboBox()
        self.comboBox.setCurrentIndex(0)
        self.connect(self.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.ComboChange)
        self.connect(self.ButtonSaveChanges, QtCore.SIGNAL("clicked()"), self.SaveCurrent)
        self.connect(self.ButtonDeleteEvent, QtCore.SIGNAL("clicked()"), self.Delete)
        self.ComboChange()
        
    def PopulateComboBox(self):
        self.comboBox.clear()
        Events = self.Database.Events.GetAllEvents()
        for E in Events:
            self.comboBox.addItem("""ID:%d  EventName:%s"""% (E.EID, E.EventName))
        
        
        
        
    def ComboChange(self):
        try:
            ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
        except:
            pass
        Event = self.Events.GetEvent(EID = ID)
        self.EventNameEdit.setText(Event.EventName)
        self.EventDescEdit.setText(Event.EventDesc)
        self.StartDateEdit.setDate( QtCore.QDate(Event.StartDate.year, Event.StartDate.month, Event.StartDate.day))
        self.EndDateEdit.setDate( QtCore.QDate(Event.EndDate.year, Event.EndDate.month, Event.EndDate.day))
        
    def SaveCurrent(self):
        ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
        StartDate = datetime.date(self.StartDateEdit.date().year(),
                                  self.StartDateEdit.date().month(),
                                  self.StartDateEdit.date().day())
        EndDate = datetime.date(self.EndDateEdit.date().year(),
                                self.EndDateEdit.date().month(),
                                self.EndDateEdit.date().day())
        
        self.Events.UpdateEvent(ID,
                                self.EventNameEdit.text(),
                                StartDate,
                                EndDate,
                                self.EventDescEdit.text())
        self.ComboChange()
        
    def Delete(self):
        self.ConfirmDiag = ConfirmDiag("""Are you sure you want to delete %s"""%(self.EventNameEdit.text()))
        self.ConfirmDiag.show()
        self.ConfirmDiag.setModal(True)
        self.connect(self.ConfirmDiag, QtCore.SIGNAL("accepted()"), self.DeleteAccepted)

    def DeleteAccepted(self):
        ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
        self.Events.RemoveEvent(ID)
        self.PopulateComboBox()
        
class AdminEditPeople(QtGui.QDialog, Ui_AdminUserDetailsDiag):
    def __init__(self, People):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.People = People
        
        self.PopulateComboBox()
        
        self.connect(self.SaveChangesButton, QtCore.SIGNAL("clicked()"), self.SaveCurrent)
        self.connect(self.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.ComboChange)
        self.connect(self.ButtonDeleteUser, QtCore.SIGNAL("clicked()"), self.DeleteUser)
    
    def DeleteUser(self):
        self.ConfirmDiag = ConfirmDiag("""Are you sure you want to delete %s %s"""%(self.LineEditFirstName.text(), self.LineEditSecondName.text()))
        self.ConfirmDiag.show()
        self.connect(self.ConfirmDiag, QtCore.SIGNAL("accepted()"), self.DeleteUserAccepted)

    def DeleteUserAccepted(self):
        ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
        self.People.RemovePerson(ID)
        #self.PopulateComboBox()
        
        
    def ComboChange(self):
        if self.comboBox.currentText() == "New User":
            self.LineEditId.setText('')
            self.LineEditFirstName.setText('')
            self.LineEditSecondName.setText('')
            self.LineEditUserName.setText('')
            self.checkBox.setCheckState(False)
        else:
            ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
            Person = self.People.GetPerson(PID = ID)
            self.LineEditId.setText(str(Person.PID))
            self.LineEditFirstName.setText(Person.f_Name)
            self.LineEditSecondName.setText(Person.l_Name)
            self.LineEditUserName.setText(Person.UserName)
            if Person.Admin:
                self.checkBox.setCheckState(True)
                self.checkBox.setTristate(False)
            else:
                self.checkBox.setCheckState(False)
        
    
    def SaveCurrent(self):
        if self.comboBox.currentText() == "New User":
            self.People.AddPerson(self.LineEditFirstName.text(), self.LineEditSecondName.text(),
                                  self.LineEditUserName.text())
            if self.checkBox.checkState():
                Person = self.People.GetPerson(f_name=self.LineEditFirstName.text(),
                                           l_name = self.LineEditSecondName.text(),
                                           UserName = self.LineEditUserName.text())
                Person.Admin = True
                self.People.UpdatePerson(Person)
            
            
        else:
            ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
            Person = self.People.GetPerson(PID = ID)
            Person.f_Name = self.LineEditFirstName.text()
            Person.l_Name = self.LineEditSecondName.text()
            Person.UserName = self.LineEditUserName.text()
            if self.checkBox.checkState():
                Person.Admin = True
            else:
                Person.Admin = False
            
            self.People.UpdatePerson(Person)
        #self.PopulateComboBox()
        
    
    def PopulateComboBox(self):
        self.comboBox.clear()
        self.comboBox.addItem("New User")
        Peps = self.People.GetAllPeople()
        for P in Peps:
            self.comboBox.addItem("""ID:%d  Name:%s %s"""% (P.PID, P.f_Name, P.l_Name))
        
class SignIn(QtGui.QDialog, Ui_SignInDiag):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        
class ModifyDetails(QtGui.QDialog, Ui_UserDetailsDiag):
    def __init__(self, ID, f_Name,l_Name,UserName):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.LineEditId.setText(str(ID))
        self.LineEditFirstName.setText(f_Name)
        self.LineEditSecondName.setText(l_Name)
        self.LineEditUserName.setText(UserName)

class ViewExpenseSummary(QtGui.QDialog, Ui_ViewExpenseSummaryDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        global PID
        global EventId
        self.CurrentPID = PID
        self.Editible = True
        
        self.PopulateComboBox()
        self.PopulateGroupExpenses()
        self.connect(self.DoneButton, QtCore.SIGNAL("clicked()"), self.EventDoneButton)
    
    def PopulateComboBox(self):
        self.comboBox.clear()
        People = self.Database.GetPeopleOnEvent(EventId)
        index = 0
        for Person in People:
            if Person.PID == self.CurrentPID:
                index = self.comboBox.count()
            self.comboBox.addItem("""%s %s"""%(Person.f_Name, Person.l_Name))
            self.comboBox.setItemData(self.comboBox.count()-1, Person.PID)
        self.comboBox.setCurrentIndex(index)
        self.connect(self.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.ComboChange)
    
    def ComboChange(self):
        self.UpdateTripExpenseStatus()
        self.CurrentPID = self.comboBox.itemData(self.comboBox.currentIndex()).toInt()[0]
        if self.CurrentPID != PID:
            self.Editible = False
        else:
            self.Editible = True
        self.PopulateGroupExpenses()
    
    def PopulateGroupExpenses(self):
        global EventId
        Total = 0.0
        while(self.tableWidget_2.rowCount() > 0):
            self.tableWidget_2.removeRow(0)
        Expenses = self.Database.GetExpensesOfPerson(EventId, self.CurrentPID)
        Statuses = self.Database.TripExpenseStatus.GetPersonsAccepts(self.CurrentPID, EventId)
        for Expense,Prop in Expenses:
            self.tableWidget_2.insertRow(self.tableWidget_2.rowCount())
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s"""%(Expense.Desc.split('\n\n')[0])))
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Expense.Amount)))
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 2, QtGui.QTableWidgetItem("""$%0.2f"""%(Prop*Expense.Amount)))
            self.tableWidget_2.setCellWidget(self.tableWidget_2.rowCount()-1, 3, QtGui.QCheckBox())
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).setTristate(False)
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).uniqueId = """%d"""%Expense.TexID
            if Expense.TexID in Statuses.keys():
                State = int(Statuses[Expense.TexID])
            else:
                State = 0
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).setCheckState(State)
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 3).setEnabled(self.Editible)
            Total = Total + Prop * Expense.Amount
            
            
        while(self.tableWidget_3.rowCount() > 0):
            self.tableWidget_3.removeRow(0)
        Expenses = self.Database.GetSubgroupExpensesOfPerson(self.CurrentPID, EventId)
        for Expense,Prop in Expenses:
            self.tableWidget_3.insertRow(self.tableWidget_3.rowCount())
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s"""%(Expense.Desc.split('\n\n')[0])))
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Expense.Amount)))
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 2, QtGui.QTableWidgetItem("""$%0.2f"""%(Prop*Expense.Amount)))
            Total = Total + Prop * Expense.Amount
            self.tableWidget_3.setCellWidget(self.tableWidget_3.rowCount()-1, 3, QtGui.QPushButton("Edit"))
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 3).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 3).clicked.connect(self.OnEditEvent)
            
            self.tableWidget_3.setCellWidget(self.tableWidget_3.rowCount()-1, 4, QtGui.QCheckBox())
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 4).setTristate(False)
            
            
        self.lineEdit_2.setText("""$%0.2f"""%Total)
            
    def OnEditEvent(self):
        SGExpId =  int(self.sender().uniqueId)
        self.EditExpenseDiag = AddSubGroupExpense(self.Database, SGExpId)
        self.EditExpenseDiag.show()
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("accepted()"), self.PopulateGroupExpenses)
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateGroupExpenses)
        
    def EventDoneButton(self):
        print "Finished"
        self.UpdateTripExpenseStatus()
        self.accept()
        
    def UpdateTripExpenseStatus(self):
        if self.Editible:
            i = 0
            global EventId
            Statuses = self.Database.TripExpenseStatus.GetPersonsAccepts(self.CurrentPID, EventId)
            while i < self.tableWidget_2.rowCount():
                TExp = int(self.tableWidget_2.cellWidget(i, 3).uniqueId)
                if TExp in  Statuses.keys():
                    self.Database.TripExpenseStatus.UpdateEventPeople(EventId, self.CurrentPID, TExp,
                                                                      int(self.tableWidget_2.cellWidget(i, 3).checkState()))
                else:
                    self.Database.TripExpenseStatus.AddPersonExpenseStatus(self.CurrentPID, EventId,
                                                                           TExp, int(self.tableWidget_2.cellWidget(i, 3).checkState()))
                i = i + 1
                #self.Database.TripExpenseStatus
            
class ViewSpendingSummary(QtGui.QDialog, Ui_ViewSpendingSummaryDiag):
    def __init__(self, Database):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Database = Database
        global PID
        global EventId
        self.CurrentPID = PID
        
        self.PopulateSpendingTable()
        
    def PopulateSpendingTable(self):
        global EventId
        Total = 0.0
        while(self.tableWidget_2.rowCount() > 0):
            self.tableWidget_2.removeRow(0)
        Expenses = self.Database.Expenses.GetExpenses(EID=EventId, PID = self.CurrentPID)
        for Expense in Expenses:
            self.tableWidget_2.insertRow(self.tableWidget_2.rowCount())
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s"""%(Expense.Desc.split('\n\n')[0])))
            self.tableWidget_2.setItem(self.tableWidget_2.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Expense.Amount)))
            Total = Total + Expense.Amount
            self.tableWidget_2.setCellWidget(self.tableWidget_2.rowCount()-1, 2, QtGui.QPushButton("Edit"))
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 2).uniqueId = """%d"""%Expense.TexID
            self.tableWidget_2.cellWidget(self.tableWidget_2.rowCount()-1, 2).clicked.connect(self.OnEditGroupExpense)
        while(self.tableWidget_3.rowCount() > 0):
            self.tableWidget_3.removeRow(0)
        Expenses = self.Database.SubGroupExpenses.GetSubGroupExpenses(EID=EventId, PID = self.CurrentPID)
        for Expense in Expenses:
            self.tableWidget_3.insertRow(self.tableWidget_3.rowCount())
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 0, QtGui.QTableWidgetItem("""%s"""%(Expense.Desc.split('\n\n')[0])))
            self.tableWidget_3.setItem(self.tableWidget_3.rowCount()-1, 1, QtGui.QTableWidgetItem("""$%0.2f"""%(Expense.Amount)))
            Total = Total + Expense.Amount
            self.tableWidget_3.setCellWidget(self.tableWidget_3.rowCount()-1, 2, QtGui.QPushButton("Edit"))
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 2).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget_3.cellWidget(self.tableWidget_3.rowCount()-1, 2).clicked.connect(self.OnEditSubGroupExpense)
        
        
        self.lineEdit_2.setText("""$%0.2f"""%Total)
        
    def OnEditGroupExpense(self):
        TExpId =  int(self.sender().uniqueId)
        self.EditExpenseDiag = EditTripExpense(self.Database, TExpId)
        self.EditExpenseDiag.show()
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("accepted()"), self.PopulateSpendingTable)
        self.connect(self.EditExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateSpendingTable)
        
    def OnEditSubGroupExpense(self):
        SgExpId =  int(self.sender().uniqueId)
        self.EditGroupExpenseDiag = AddSubGroupExpense(self.Database, SgExpId)
        self.EditGroupExpenseDiag.show()
        self.connect(self.EditGroupExpenseDiag, QtCore.SIGNAL("accepted()"), self.PopulateSpendingTable)
        self.connect(self.EditGroupExpenseDiag, QtCore.SIGNAL("rejected()"), self.PopulateSpendingTable)
      
      
      
      
      
      
      
      
      
      
      
      
    
        
class TripExpensesMainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)    
        self.setupUi(self)
        
        ##Setup the connection with the MYSQL Database
        self.Database = DataBase.Database()

        
        ##This is the Person object of the person that signed in.
        global PID
        global Admin
        global EventId
        PID = -1
        Admin = False
        EventId = -1
        
        self.SignInStart()
        
        
        

        
    def InitActions(self):
        global Admin
        self.connect(self.actionModify_Details, QtCore.SIGNAL("triggered()"), self.ActionModifyPersonalDetails)
        self.connect(self.actionAdd_Person,QtCore.SIGNAL("triggered()"), self.ActionAddNewPerson)
        self.connect(self.actionManage_People_On_Event,QtCore.SIGNAL("triggered()"), self.ActionManagePeopleOnEvent)
        self.connect(self.actionEdit_Dates_On_Event,QtCore.SIGNAL("triggered()"), self.ActionEditDateOnEvent)
        self.connect(self.actionAdd_Expenses,QtCore.SIGNAL("triggered()"), self.ActionAddTripExpenseEvent)
        self.connect(self.actionView_Expenses,QtCore.SIGNAL("triggered()"), self.ActionViewTripExpense)
        self.connect(self.actionAdd_Subgroup_Expense, QtCore.SIGNAL("triggered()"), self.ActionAddSubgroupExpense)
        self.connect(self.actionView_Subgroup_Expenses, QtCore.SIGNAL("triggered()"), self.ActionViewSubgroupExpense)
        self.connect(self.actionView_Expense_Summary, QtCore.SIGNAL("triggered()"), self.ActionViewExpenseSummary)
        self.connect(self.actionView_Spending_Summary, QtCore.SIGNAL("triggered()"), self.ActionViewSpendingSummary)
        
        if Admin:
            self.actionEdit_People.setEnabled(True)
            self.connect(self.actionEdit_People, QtCore.SIGNAL("triggered()"), self.ActionEdit_People)
            #self.connect(self.actionAdd_Event, QtCore.SIGNAL("triggered()"), self.ActionAdd_Event)
            self.connect(self.actionEdit_Event, QtCore.SIGNAL("triggered()"), self.ActionEdit_Events)
        
        else:
            self.actionEdit_People.setEnabled(False)
            self.actionEdit_Event.setEnabled(False)
                    
    def Exit(self):
        self.close()
        
    def SignInStart(self):
        self.SigninDiag = SignIn()
        self.SigninDiag.show()
        self.connect(self.SigninDiag, QtCore.SIGNAL("accepted()"), self.SignInNameEntered)
        self.connect(self.SigninDiag, QtCore.SIGNAL("rejected()"), self.Exit)
    
    def SignInNameEntered(self):
        global Admin
        global PID
        UsrName = self.SigninDiag.NameEdit.text()
        if UsrName == '':
            self.SignInStart()
        else:
            Person = self.Database.People.GetPerson(UserName = UsrName)
            if Person != None:
                PID = Person.PID
                Admin = Person.Admin
                self.SignInSelectEvent()
            else:
                print "Fail"
                self.SignInStart()
                      
    def SignInSelectEvent(self):
        global Admin
        global PID
        if Admin:
            self.SelectEventDiag = SelectEventAdmin(self.Database)
        else:
            self.SelectEventDiag = SelectEvent(self.Database)
        self.SelectEventDiag.show()
        
        self.connect(self.SelectEventDiag, QtCore.SIGNAL("accepted()"), self.SignInEventEntered)
        self.connect(self.SelectEventDiag, QtCore.SIGNAL("rejected()"), self.Exit)
                
    def SignInEventEntered(self):
        global EventId
        EventId = self.SelectEventDiag.GetEvent()
        self.InitActions()
        self.PopulateMainWindow()
        
    def ActionModifyPersonalDetails(self):
        print self.PID
        Person = self.People.GetPerson(PID = self.PID)
        if Person != None:
            self.UserDetailsDiag = ModifyDetails(Person.PID, Person.f_Name, Person.l_Name, Person.UserName)
            self.UserDetailsDiag.show()
            self.connect(self.UserDetailsDiag, QtCore.SIGNAL("accepted()"), self.ModifyPersonalDetailsAccept)
    
    def ModifyPersonalDetailsAccept(self):
        Person = self.People.GetPerson(PID = self.PID)
        Person.f_Name = self.UserDetailsDiag.LineEditFirstName.text()
        Person.l_Name = self.UserDetailsDiag.LineEditSecondName.text()
        Person.UserName = self.UserDetailsDiag.LineEditUserName.text()
        self.People.UpdatePerson(Person)
        
    def ActionAddNewPerson(self):
        self.AddNewPersonDiag = AddNewPerson()
        self.AddNewPersonDiag.show()
        self.connect(self.AddNewPersonDiag, QtCore.SIGNAL("accepted()"), self.AddNewPersonAccept)
        
    def AddNewPersonAccept(self):
        print "Accepted"
        
    def ActionAdd_Event(self):
        self.AddEventDiag = AdminCreateNewEvent()
        self.AddEventDiag.show()
        self.connect(self.AddEventDiag, QtCore.SIGNAL("accepted()"), self.ActionAdd_EventAccept)
        
    def ActionAdd_EventAccept(self):
        StartDate = datetime.date(self.AddEventDiag.StartDateEdit.date().year(),
                                  self.AddEventDiag.StartDateEdit.date().month(),
                                  self.AddEventDiag.StartDateEdit.date().day())
        EndDate = datetime.date(self.AddEventDiag.EndDateEdit.date().year(),
                                self.AddEventDiag.EndDateEdit.date().month(),
                                self.AddEventDiag.EndDateEdit.date().day())
        self.Events.AddEvent(self.AddEventDiag.EventNameEdit.text(),
                             StartDate,
                             EndDate,
                             self.AddEventDiag.EventDescEdit.text())
        self.SignInSelectEvent()
        
    def ActionEdit_People(self):
        self.EditPeopleDiag = AdminEditPeople(self.People)
        self.EditPeopleDiag.show()
        
    def ActionEdit_Events(self):
        self.EditEventsDiag = AdminEditEvent(self.Database)
        self.EditEventsDiag.show()
        
    def ActionManagePeopleOnEvent(self):
        self.ManagePeopleOnEventDiag = ManagePeopleOnEvent(self.Database)
        self.ManagePeopleOnEventDiag.show()
  
    def ActionEditDateOnEvent(self):
        self.EditDatesOnEventDiag = DatesOnEventDiag(self.Database)
        self.EditDatesOnEventDiag.show()
        
    def ActionAddTripExpenseEvent(self):
        self.AddTripExpenseDiag = EditTripExpense(self.Database)
        self.AddTripExpenseDiag.show()
  
    def ActionViewTripExpense(self):
        self.VeiwTripExpensesDiag = ViewTripExpense(self.Database)
        self.VeiwTripExpensesDiag.show()
        
    def ActionAddSubgroupExpense(self):
        self.AddSubGroupExpenseDiag = AddSubGroupExpense(self.Database)
        self.AddSubGroupExpenseDiag.show()

    def ActionViewSubgroupExpense(self):
        self.ViewSubGroupExpenseDiag = ViewSubGroupExpense(self.Database)
        self.ViewSubGroupExpenseDiag.show()
            
    def ActionViewExpenseSummary(self):
        self.ViewExpenseSummaryDiag = ViewExpenseSummary(self.Database)
        self.ViewExpenseSummaryDiag.show()
        
    def ActionViewSpendingSummary(self):
        self.ViewSpendingSummaryDiag = ViewSpendingSummary(self.Database)
        self.ViewSpendingSummaryDiag.show()
            
        
    def PopulateMainWindow(self):
        global EventId
        EventInfo = self.Database.Events.GetEvent(EID = EventId)[0]
        self.EventNameDisp.setText(EventInfo.EventName)
        self.StartDateDisp.setText("""%d/%d/%d"""%(EventInfo.StartDate.day,EventInfo.StartDate.month,EventInfo.StartDate.year))
        self.EndDateDisp.setText("""%d/%d/%d"""%(EventInfo.EndDate.day,EventInfo.EndDate.month,EventInfo.EndDate.year))
        
        #self.PopulateMainWindowSpread()
         
    def PopulateMainWindowSpread(self):
        print 'tick'
        self.GetDataThread = GetMainDataThread(self.People, self.Events, self.PeopleOnEvents,
                                               self.TripExpenses, self.SubGroupExpenses, self.EventId)
        self.connect(self.GetDataThread, QtCore.SIGNAL("update(PyQt_PyObject)"), self.PopulateMainWindowSpreadDataRec)
        self.GetDataThread.start()
    
    def PopulateMainWindowSpreadDataRec(self, Data):
        while(self.MainPagetable.rowCount() > 0):
            self.MainPagetable.removeRow(0)
        for Line in Data:
            self.MainPagetable.insertRow(self.MainPagetable.rowCount())
            i = 0
            while i < len(Line):
                self.MainPagetable.setItem(self.MainPagetable.rowCount()-1, i, QtGui.QTableWidgetItem("""%s"""%Line[i]))
                i = i + 1
        i = 0
        while (i < self.MainPagetable.columnCount()):
            self.MainPagetable.resizeColumnToContents(i)
            i = i + 1
        self.Timer.start()

class GetMainDataThread(QtCore.QThread):
    def __init__(self, People, Events, PeopleOnEvents, TripExpenses, SubGroupExpenses, EventId):
        QtCore.QThread.__init__(self)
        self.People = People
        self.Events = Events
        self.PeopleOnEvents = PeopleOnEvents
        self.TripExpenses = TripExpenses
        self.EventId = EventId
        self.SubGroupExpenses = SubGroupExpenses
        
        
    def run(self):
        PeopleOnEvent = self.PeopleOnEvents.GetAllPeopleOnEvent(self.EventId)
        TotalManDays =  self.PeopleOnEvents.GetTotalEventManDays(self.EventId)
        TotalEventCost = self.TripExpenses.GetTotalEventCost(self.EventId)
        People = self.People.GetAllPeopleDict()
        Data = []
        for PID, Dates in PeopleOnEvent:
            Line = []
            Person = People[PID]
            Person = self.People.GetPerson(PID = PID)
            Line.append("""%s %s"""%(Person.f_Name, Person.l_Name))
            
            AmountSpentByPerson = self.TripExpenses.GetTotalSpentByPersonOnEvent(PID, self.EventId)
            Line.append("""$%.2f"""%round(AmountSpentByPerson,2))
            
            PersonsManDays = self.PeopleOnEvents.GetPersonsManDays(Dates = Dates)
            Line.append("""$%.2f"""%round(float((PersonsManDays/TotalManDays)*TotalEventCost),2))
            
            AmountSpentByPerson = self.SubGroupExpenses.GetTotalSpentByPersonOnSubGroups(PID, self.EventId)
            Line.append("""$%.2f"""%round(AmountSpentByPerson,2))
            
            Data.append(Line)
            
            
        
        self.emit( QtCore.SIGNAL('update(PyQt_PyObject)'), Data)
        return


    
        
        
app = QtGui.QApplication(sys.argv)
form = TripExpensesMainWindow()
form.show()
app.exec_()